#include "widget.h"
#include "ui_widget.h"

#include<QMessageBox>
#include<QTcpSocket>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //设置窗口标题
    this->setWindowTitle("服务器");
    //实例化TCP server
    tcpServer=new QTcpServer(this);
    //通过信号槽，处理客户端建立的新连接
    //newConnection信号
    connect(tcpServer,&QTcpServer::newConnection,this,&Widget::processConnection);
    qDebug()<<"server connect success!";
    //监听端口
    bool ret=tcpServer->listen(QHostAddress::Any,8081);
    qDebug()<<"server listen:"<<ret;
    if(!ret)
    {
        QMessageBox::critical(this,"监听失败",tcpServer->errorString());
        return;
    }
}

Widget::~Widget()
{
    delete ui;
}

void Widget::processConnection()
{
    //获取到新的连接对应的socket
    QTcpSocket*clientsocket=tcpServer->nextPendingConnection();
    qDebug()<<"server nextPendingConnection success!";
    QString log=QString("[")+clientsocket->peerAddress().toString()+":"+QString::number(clientsocket->peerPort())+"]"
            +"客户端上线了";
    ui->listWidget->addItem(log);

    //通过信号槽，处理收到请求的情况
    connect(clientsocket,&QTcpSocket::readyRead,this,[=](){
        //1.读取请求
        const QString& request=clientsocket->readAll();
        //2.根据请求处理响应
        const QString &response=process(request);
        //3.把响应写到客户端
        clientsocket->write(response.toUtf8());


        QString log1="["+clientsocket->peerAddress().toString()+":"+QString::number(clientsocket->peerPort())
                +"]"+"req:"+request+",rsp:"+response;
        ui->listWidget->addItem(log1);
    });
    //通过信号槽，处理断开连接的情况  disconnection   删除clientsocket---deletelater
    connect(clientsocket,&QTcpSocket::disconnected,this,[=](){
        QString log2="["+clientsocket->peerAddress().toString()+":"+clientsocket->peerPort()+"]"
                +"客户端下线了";
        ui->listWidget->addItem(log2);
        clientsocket->deleteLater();
    });
}

QString Widget::process(QString request)
{
    return request;
}

